const list = [
  { id: 1, pid: 0, name: "四川" },
  { id: 2, pid: 1, name: "成都" },
  { id: 3, pid: 1, name: "宜宾" },
  { id: 4, pid: 1, name: "绵阳" },
  { id: 5, pid: 1, name: "德阳" },
  { id: 6, pid: 2, name: "高新区" },
  { id: 7, pid: 2, name: "武侯区" },
  { id: 8, pid: 3, name: "翠屏区" },
];

const arrToTree = (arr, pid) => {
  return arr.reduce((pre, cur) => {
    if (cur["pid"] === pid) {
      cur.children = arrToTree(arr, cur["id"]);
      return pre.concat(cur);
    }
    return pre;
  }, []);
};

console.log(arrToTree(list, 0));

// 方法二：hash表 + 引用关系，传入数组，根结点ID，返回一个输结构对象
const arrToTreeByHash = (arr, rootId) => {
  const map = {};
  for (const item of arr) {
    map[item["id"]] = item;
  }

  for (item of arr) {
    const key = item["pid"];
    if (!(key in map)) {
      continue;
    }
    map[key].children = (map[key].children || []).concat(item);
  }
  return map[rootId];
};
console.log(arrToTreeByHash(list, 1));
